package com.youdoneed.community.group.web;

import com.google.gson.Gson;
import com.youdoneed.base.application.AppException;
import com.youdoneed.base.common.JWTUtils;
import com.youdoneed.community.common.utils.BaiduTranslate;
import com.youdoneed.community.common.vo.PageData;
import com.youdoneed.community.common.vo.ResultMessage;
import com.youdoneed.community.group.entity.Forumgroup;
import com.youdoneed.community.group.service.ForumgroupService;
import com.youdoneed.community.group.service.ForumgroupStatic;
import com.youdoneed.community.group.vo.BatchVo;
import com.youdoneed.community.group.vo.ForumInUserGroupVo;
import com.youdoneed.community.group.vo.ForumgroupBatchVo;
import com.youdoneed.community.group.vo.ForumgroupInUserVo;
import com.youdoneed.community.group.vo.ForumgroupVo;
import com.youdoneed.community.group.vo.GroupAndUserList;
import com.youdoneed.community.group.vo.HuanxinData;
import com.youdoneed.community.group.vo.HuanxinGroupDetail;
import com.youdoneed.friends.feign.FriendsClient;
import com.youdoneed.user.feign.UserFeignClient;
import com.youdoneed.user.model.User;
import com.youdoneed.user.vo.UserBasicInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 小组模块控制器
 *
 * @author lid
 * @date 2017.6.24
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping(value = "/forumgroup", method = {RequestMethod.GET, RequestMethod.POST})
@Api(value = "小组模块控制器", description = "小组模块控制器")
public class ForumgroupController {

    private final Logger logger = LoggerFactory.getLogger(ForumgroupController.class);
    
    private static final Gson GSON = new Gson();
    
    @Autowired
    ForumgroupService forumgroupService;

    @Autowired
    UserFeignClient userFeignClient;

    @Autowired
    FriendsClient friendsClient;
    /**
     * 创建小组(用户小组)
     * @param forumgroup
     * @param forumgroupvo
     * @return ResultMessage<Integer>
     * @author lixs
     * @Date 2017.7.7
     */
    @ResponseBody
    @RequestMapping(value = "/saveForumGroup", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "创建用户小组", value = "创建用户小组")
    public ResultMessage<Integer> saveForumGroup(Forumgroup forumgroup, ForumgroupVo forumgroupvo) {
        logger.info("创建用户小组");
        List<String> userId = forumgroupvo.getUserId();
        String forumgroupId = forumgroupService.saveForumGroup(forumgroup, userId);
        if (null != forumgroupId) {
            return ResultMessage.newSuccess("创建用户小组成功!").setData(forumgroupId);
        }
        return ResultMessage.newFailure("创建用户小组失败!");
    }
    
    /**
     * 创建小组（系统小组）
     * @param forumgroup
     * @return
     * @author lixs
     * @Date 2017.7.26
     */
    @RequestMapping(value = "/saveSystemForumGroup", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "创建系统小组", value = "创建系统小组")

    public ResultMessage<Integer> saveSystemForumGroup(Forumgroup forumgroup){
    	
    	logger.info("创建系统小组");
    	int result = forumgroupService.saveSystemForumGroup(forumgroup);
		if (0 != result) {
		    return ResultMessage.newSuccess("创建系统小组成功!").setData(result);
		}
		return ResultMessage.newFailure("创建系统小组失败!");
    }

    /**
     * 获取我的小组信息
     *
     * @param userId 用户id
     * @param limit  每页限制显示的数据
     * @param offset 每页起始页显示
     * @return ResultMessage<List<Forumgroup>>
     * @author lixs
     * @Date 2017.7.7
     */
    @RequestMapping(value = "/getMyGroups", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取我的小组信息", value = "获取我的小组信息")
    public ResultMessage<PageData> getMyGroups(Integer offset,Integer limit,
                                                       	  @ApiParam("用户id") @RequestParam String userId) {
        logger.info(" 获取我的小组信息!getMyGroups");
        List<Forumgroup> listForumgroup = forumgroupService.getMyGroups(userId, limit, offset);
        if (null == listForumgroup) {
            return ResultMessage.newFailure("获取我的小组信息失败!");
        }
        
        PageData page = new PageData();
        page.setRows(listForumgroup);
        page.setTotal(forumgroupService.countGroupByUserId(userId));
        return ResultMessage.newSuccess("获取我的小组信息成功!").setData(page);
    }
    
   

   /* *//**
     * 搜索附近的小组(公开群)
     *
     * @param longitude
     * @param latitude
     * @return ResultMessage
     * @author lid
     * @date 2017.6.25
     *//*
    @RequestMapping(value = "/getNearByGroups", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "搜索附近的小组", value = "搜索附近的小组")
    public ResultMessage<PageData> getNearByGroups(@ApiParam("经度") @RequestParam Double longitude,
    														 @ApiParam("纬度") @RequestParam Double latitude,
    														 @ApiParam("距离（米）") @RequestParam Integer distance,
    														 @ApiParam("用户id") @RequestParam String userId,
    														 Integer offset,Integer limit,
    														 @RequestHeader(value = "Authorization") String token) {

        logger.info(" 获取我的小组信息!getMyGroups");
//        double distanceD = distance * 1000;
      //判断是否有距离设置以及用户是否提供了GPS定位数据
        if ((null != distance) && (null != latitude) && (null != longitude)) {
            logger.info("GPS定位数据以及距离设置数据获取正常！distance=" + distance +
                    ",latitude=" + latitude + ",longitude=" + longitude);

            List<ForumInUserGroupVo> forumInUserGroupVo = forumgroupService.getNearByGroups(longitude, latitude,distance,userId,offset,limit);
            if (null == forumInUserGroupVo) {
                return ResultMessage.newFailure("获取附近的小组信息失败!");
            }
            List<ForumInUserGroupVo> listForumgroupTotal = forumgroupService.getNearByGroupsTotal(longitude, latitude, distance, userId);
            if (null == listForumgroupTotal) {
                return ResultMessage.newFailure("获取附近的小组总数失败!");
            }
            PageData page = new PageData();
            page.setRows(forumInUserGroupVo);
            page.setTotal(listForumgroupTotal.size());
            return ResultMessage.newSuccess("获取附近小组信息成功").setData(page);
        }

        return ResultMessage.newFailure("GPS定位数据异常！");

    }*/

    /*
     * 测试
     * @param userId
     * @param groupId
     * @author lixs
     * @Date 2017.6.28
     */
   /* @RequestMapping(value = "/joinGroup", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "测试", value = "测试")
    public ResultMessage<Boolean> joinGroup() {
        logger.info("加入小组");
        return ResultMessage.newSuccess("成功加入小组").setData(userFeignClient.userFocusRegions().getData().size());
    }*/

    /**
     * 退出小组
     *
     * @param userId
     * @param groupId
     * @author lixs
     * @Date 2017.6.28
     */
    @RequestMapping(value = "/quitGroup", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "退出小组", value = "退出小组")
    public ResultMessage<Boolean> quitGroup(@ApiParam("用户id") @RequestParam String userId,
    										@ApiParam("小组id") @RequestParam String groupId) {
        logger.info("退出小组");
        Boolean result = forumgroupService.quitGroup(userId, groupId);
        if (result == false) {
            return ResultMessage.newFailure("退出小组失败").setData(result);
        }
        return ResultMessage.newSuccess("成功退出小组").setData(result);
    }

    /**
     * 获取小组成员信息
     * @param groupId
     * @param limit
     * @param offset
     * @author lixs
     * @Date 2017.6.8
     */
    @RequestMapping(value = "/getMembersInGroup", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取小组成员信息", value = "获取小组成员信息")
    public ResultMessage<PageData> getMembersInGroup(@ApiParam("小组id") @RequestParam String groupId) {
        logger.info("获取小组成员信息");
        Forumgroup forumgroup =forumgroupService.selectGroupById(groupId);
	  	  if(forumgroup==null){
	  		  return ResultMessage.newFailure("未查到该小组");
	  	  }
	  	  if(forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)){
	  		  return ResultMessage.newFailure("该群组已被解散");
	  	  }
        List<String> userIds = forumgroupService.getMembersInGroup(groupId);
        if (userIds == null) {
            return ResultMessage.newFailure("获取小组成员id失败");
        }
        com.youdoneed.base.application.ResultMessage<List<User>> result
                = userFeignClient.getUsers(userIds.toArray(new String[userIds.size()]));
        if (!result.isSuccess())
            return ResultMessage.newFailure("获取小组成员信息失败").setData("{}");
        PageData page = new PageData();
        page.setRows(result.getData());
        page.setTotal(userIds.size());
        return ResultMessage.newSuccess("获取小组成员信息成功").setData(page);
    }

    /**
     * 小组的设置
     * @param forumgroup
     * @author lixs
     * @date 2017.7.7
     */
    @RequestMapping(value = "/groupPrivacySetting", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "小组的设置", value = "小组的设置")
    public ResultMessage<Integer> groupPrivacySetting(@ApiParam("小组id") @RequestParam String forumGroupId,
    												  @ApiParam("小组名称") @RequestParam String groupName,
    												  @ApiParam("小组简介") @RequestParam String groupIntroduction,
    												  @ApiParam("小组隐私设置") @RequestParam Integer privacySetting,
    												  Double longitude,
    												  Double latitude,
    												  @ApiParam("小组类别") @RequestParam String groupStyle,
    												  String address) {
        logger.info("小组的设置");
        int result = forumgroupService.groupPrivacySetting(forumGroupId, groupName, groupIntroduction, privacySetting, longitude, latitude,groupStyle,address);
        if (result == 0) {
            return ResultMessage.newFailure("小组设置失败");
        }
        return ResultMessage.newSuccess("小组设置成功").setData(result);
    }
    
    /**
     * 通过名字查询小组成员(不分页)
     * 
     * @param groupId
     * @param userName
     * @author lixs
     * @Date 2017.7.10
     * 
     */
    @RequestMapping(value = "/findUser", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "通过名字查询小组成员", value = "通过名字查询小组成员")
    public ResultMessage<List<UserBasicInfo>> findUser(@ApiParam("小组id") @RequestParam String groupId, String userName){
    	  logger.info("通过模糊查询来查找用户信息");
    	  Forumgroup forumgroup =forumgroupService.selectGroupById(groupId);
	  	  if(forumgroup==null){
	  		  return ResultMessage.newFailure("未查到该小组");
	  	  }
    	  List<String> userIds = forumgroupService.getMembersInGroup(groupId);
          if (userIds == null) {
              return ResultMessage.newFailure("获取小组成员id失败");
          }
          String[] ids = userIds.toArray(new String[userIds.size()]);
          logger.info("ids的大小"+userIds.size());
          logger.info("数量"+ids[0]);
    	  com.youdoneed.base.application.ResultMessage<List<UserBasicInfo>> result= userFeignClient.findInUserIds(ids, userName);
    	  if (!result.isSuccess()){
              return ResultMessage.newFailure("获取小组成员信息失败").setData("{}");
    	  }
    	  return ResultMessage.newSuccess("查询成功").setData(result.getData());
    }
    
    /**
     * 通过小组名模糊查询来查找小组信息（只查出公开群和封闭群）
     * @param groupName
     * @param limit
     * @param offset
     * @author lixs
     * @Date 2017.7.12
     */
    @RequestMapping(value = "/selectByGroupName", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "通过小组名模糊查询来查找小组信息", value = "通过小组名模糊查询来查找小组信息")
    public ResultMessage<PageData> selectByGroupName(String userId,String groupName, Integer limit,Integer offset){
    	logger.info("通过小组名模糊查询来查找小组信息");
    	List<ForumInUserGroupVo> forumgroup = forumgroupService.selectByGroupName(userId, groupName, offset, limit);
    	if(forumgroup==null){
    		return ResultMessage.newFailure("查询失败");
    	}
		 PageData page = new PageData();
	     page.setRows(forumgroup);
	     page.setTotal(forumgroupService.selectByGroupNameForTotal(userId, groupName));
    	return ResultMessage.newSuccess("查询成功").setData(page);
    }
   
    /**
     * 小组创建者移除小组成员
     * @param userId
     * @param groupId
     * @param leaderId
     * @author lixs
     * @Date 2017.7.17
     */
    @RequestMapping(value = "/quitGroupByLeader", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "小组创建者移除小组成员", value = "小组创建者移除小组成员")
    public ResultMessage<Integer> quitGroupByLeader(@ApiParam("群主id")@RequestParam String leaderUserId,
    												@ApiParam("用户id")@RequestParam String userId,
    												@ApiParam("小组id")@RequestParam String groupId){
    	logger.info("小组创建者移除小组成员");
    	int result = forumgroupService.quitGroupByLeader(leaderUserId,userId, groupId);
    	if(result==0){
    		return ResultMessage.newFailure("小组创建者移除小组成员失败");
    	}
    	return ResultMessage.newSuccess("小组创建者移除小组成员成功").setData(result);
    }
    
    /**
     * 通过小组id查询小组的详细信息
     * @param groupId
     * @author lixs
     * @Date 2017.7.24
     * .
     */
    @RequestMapping(value = "/selectGroupDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取小组详细信息", value = "获取小组详细信息")
    public ResultMessage<Forumgroup> selectGroupDetail(String groupId){
    	
    	logger.info("获取小组详细信息");
    	Forumgroup forumgroup = forumgroupService.selectGroupById(groupId);
    	if(forumgroup==null){
    		return ResultMessage.newFailure("未查到小组信息");
    	}
    	return ResultMessage.newSuccess("获取小组信息成功").setData(forumgroup);
    }
    
    /**
     * 获取环信小组详细信息
     * @param forumgroupId
     * @author lixs
     * @Date 2017.7.26
     */
    @RequestMapping(value = "/selectHuanxinGroupDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取环信小组详细信息", value = "获取环信小组详细信息")
    public ResultMessage<HuanxinData> selectHuanxinGroupDetail(String forumgroupId){
    	
    	logger.info("获取环信小组详细信息");
    	Forumgroup forumgroup = forumgroupService.selectGroupById(forumgroupId);
    	List<String> groupId = new ArrayList<String>();
    	groupId.add(forumgroup.getHuanxinGroupId());
    	//解析环信小组详情信息
    	String result = friendsClient.getGroupDetails(groupId).getData();
    	HuanxinData huanxinJson = GSON.fromJson(result, HuanxinData.class);
    	if(huanxinJson==null){
    		return ResultMessage.newFailure("查询信息失败");
    	}
    	return ResultMessage.newSuccess("查询环信小组信息成功").setData(huanxinJson.data);
    }
    
    /**
     * 多条件查询小组信息(后台管理页面接口)
     * @param groupName
     * 
     * @param privacy
     * @param createDateS
     * @param createDateE
     * @param limit
     * @param offset
     * @author lixs
     * @Date 2017.8.9
     */
    @RequestMapping(value = "/selectGroupByNameAndDate", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "多条件查询获取小组详细信息", value = "多条件查询获取小组详细信息")
    public ResultMessage<PageData> selectGroupByNameAndDate(String groupName,Integer privacy,String createDateS,String createDateE,Integer limit,Integer offset){
    	logger.info("多条件查询小组详细信息");
//    	List<Forumgroup> forumgrouptotal = forumgroupService.selectGroupByNameAndDate(groupName, privacy, createDateS, createDateE);
    	List<Forumgroup> forumgroup = forumgroupService.selectGroupByNameAndDateByPage(groupName, privacy, createDateS, createDateE, offset, limit);
    	if(forumgroup==null){
    		return ResultMessage.newFailure("未查到小组信息");
    	}
    	 PageData page = new PageData();
	     page.setRows(forumgroup);
	     page.setTotal(forumgroupService.selectGroupByNameAndDateForTotal(groupName, privacy, createDateS, createDateE));
	     logger.info("记录条数"+page.getTotal());
    	return ResultMessage.newSuccess("获取信息成功").setData(page);
    }
    
    /**
     * 获取app下的所有群组
     * @author lixs
     * @param limit 每页显示的条数
     * @param cursor 分页时所带的游标（第一次查询默认为空）
     * @Date 2017.7.27
     */
    @RequestMapping(value = "/findAllHuanxinGroupDetails", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取app下的所有群组", value = "获取app下的所有群组")
    public ResultMessage<HuanxinGroupDetail> findAllHuanxinGroupDetails(String limit,String cursor){
    	logger.info("获取app下的所有群组");
    	String result = friendsClient.getGroupUser(limit, cursor).getData();
    	HuanxinGroupDetail group = GSON.fromJson(result, HuanxinGroupDetail.class);
    	if(group==null){
    		return ResultMessage.newFailure("返回数据失败");
    	}
    	return ResultMessage.newSuccess("返回数据成功").setData(group);
    }
    
    /**
     * 首页不显示群成员帖
     * @param userId
     * @param groupId
     * @author lixs
     * @Date 2017.7.29
     */
    @RequestMapping(value = "/updateGroupMessageSetting", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "首页不显示群成员帖", value = "首页不显示群成员帖")
    public ResultMessage<Integer> updateGroupMessageSetting(@ApiParam("用户id")@RequestParam String userId,
															@ApiParam("小组id")@RequestParam String groupId,
															@ApiParam("是否显示成群帖的状态")@RequestParam Integer status){
    	
    	logger.info("首页不显示群成员帖");
    	int result = forumgroupService.updateGroupMessageSetting(groupId, userId,status);
    	if(0==result){
    		return ResultMessage.newFailure("首页不显示群成员帖失败");
    	}
    	return ResultMessage.newSuccess("首页不显示群成员帖成功").setData(result);
    }                
    
    /**
     * 群聊消息免打扰
     * @param userId
     * @param groupId
     * @param status
     * @author lixs
     * @Date 2017.8.8
     */
    @RequestMapping(value = "/updateGroupChatSetting", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "群聊消息免打扰", value = "群聊消息免打扰")
    public ResultMessage<Integer> updateGroupChatSetting(@ApiParam("用户id")@RequestParam String userId,
												   @ApiParam("小组id")@RequestParam String groupId,
												   @ApiParam("群聊免打扰的状态")@RequestParam Integer status){
    	logger.info("群聊消息免打扰");
    	int result = forumgroupService.updateGroupChatSetting(userId, groupId, status);
    	if(result==0){
    		return ResultMessage.newFailure("首页不显示群成员帖设置失败");
    	}
    	return ResultMessage.newSuccess("首页不显示群成员帖设置成功").setData(result);
    }
    
    
    /**
     * 更改小组背景图片
     * @param groupId
     * @param backGroundImg
     * @author lixs
     * @Date 2017.7.29
     */
    @RequestMapping(value = "/UpdateGroupBackgroundImg", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "更改小组背景图片", value = "更改小组背景图片")
    public ResultMessage<Integer> UpdateGroupBackgroundImg(@ApiParam("小组id")@RequestParam String groupId,
    													   @ApiParam("群主id")@RequestParam String leaderUserId,
    													   @ApiParam("小组背景图片")@RequestParam String backGroundImg){
    	
    	logger.info("更改小组背景图片");
    	int result = forumgroupService.UpdateGroupBackgroundImg(groupId, backGroundImg,leaderUserId);
    	if(0==result){
    		return ResultMessage.newFailure("更改小组背景图片失败");
    	}
    	return ResultMessage.newSuccess("更改小组背景图片成功").setData(result);
    }
    
    /**
     * 获取我的好友列表(邀请好友进群时筛选掉不在群里的好友的列表)
     * @param forumgroupId
     * @param token
     * @author lixs
     * @Date 2017.7.31
     */
    @RequestMapping(value = "/findFriendList", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取我的好友列表(邀请好友进群时筛选掉不在群里的好友的列表)", value = "获取我的好友列表(邀请好友进群时筛选掉不在群里的好友的列表)")
    public ResultMessage<List<User>> findFriendList(@ApiParam("小组id")@RequestParam String forumgroupId,
    												@RequestHeader(value = "Authorization") String token){
//    	String userId = JWTUtils.getTokenUserId(token);
//    	logger.info("我的id是"+userId);
        List<User> user = forumgroupService.findFriends(forumgroupId);
        if(null==user){
        	return ResultMessage.newFailure("获取我的邀请列表失败");
        }
    	return ResultMessage.newSuccess("获取我的邀请列表成功成功").setData(user);
    }
    /**
     * 获取小组详细信息，包含与用户关联的信息
     * @param forumgroupId
     * @param userId
     * @author lixs
     * @Date 2017.7.31
     */
    @RequestMapping(value = "/findForumgroupDetails", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取小组详细信息，包含与用户关联的信息", value = "获取小组详细信息，包含与用户关联的信息")
    public ResultMessage<ForumgroupInUserVo> findForumgroupDetails(@ApiParam("小组id")@RequestParam String forumgroupId,
    											  @ApiParam("用户id")@RequestParam String userId){
    	logger.info("获取小组详细信息，包含与用户关联的信息");
    	ForumgroupInUserVo forumgroupInUserVo = forumgroupService.findForumgroupDetails(userId, forumgroupId);
    	if(null==forumgroupInUserVo){
    		return ResultMessage.newFailure("获取信息失败");
    	}
    	return ResultMessage.newSuccess("获取信息成功").setData(forumgroupInUserVo);
    }
    
    /**
     * 多条件查询小组信息
     * @param groupName
     * @param leaderUserName
     * @param groupType
     * @param groupStyle
     * @param memberCountMin
     * @param memberCountMax
     * @param groupMessageTotalMin
     * @param groupMessageTotalMax
     * @param createDateS
     * @param createDateE
     * @author lixs
     * @Date 2017.8.3
     */
    @RequestMapping(value = "/selectForumgroup", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "多条件查询小组信息(后台管理页面)", value = "多条件查询小组信息(后台管理页面)")
    public ResultMessage<PageData> selectForumgroup(String groupName,String leaderUserName,String groupType,String groupStyle,
			   												Integer memberCountMin,Integer memberCountMax,Integer groupMessageTotalMin,
			   												Integer groupMessageTotalMax,String createDateS,String createDateE,Integer offset,
			   												Integer limit){
    	
    	logger.info("多条件查询小组信息");
    	
    	List<Forumgroup> forumgroup 
    	= forumgroupService.selectForumgroup(groupName, leaderUserName, groupType, groupStyle, memberCountMin, memberCountMax,
    										groupMessageTotalMin, groupMessageTotalMax, createDateS, createDateE,offset,limit);
    	if(null==forumgroup){
    		return ResultMessage.newFailure("获取小组信息失败");
    	}
    	PageData page = new PageData();
	    page.setRows(forumgroup);
	    //page.setTotal(forumgroup.size());
	    page.setTotal(forumgroupService.countForumgroupTotal(groupName, leaderUserName, groupType, groupStyle, memberCountMin, 
				memberCountMax, groupMessageTotalMin, groupMessageTotalMax, createDateS, createDateE));
    	return ResultMessage.newSuccess("获取小组信息成功").setData(page);
    }
    
    /**
     * 获取群聊消息免打扰的群组id
     * @param userId
     * @author lixs
     * @Date 2017.8.8
     */
    @RequestMapping(value = "/selectForumgroupIdByChatSetting", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "查询出需要群聊消息免打扰的群组", value = "查询出需要群聊消息免打扰的群组")
    public ResultMessage<List<String>> selectForumgroupIdByChatSetting(String userId){
    	logger.info("查询出需要群聊消息免打扰的群组");
    	List<String> forumgroupId = forumgroupService.selectForumgroupIdByChatSetting(userId);
    	if(null==forumgroupId){
    		return ResultMessage.newFailure("查询出需要群聊消息免打扰的群组失败");
    	}
    	return ResultMessage.newSuccess("查询出需要群聊消息免打扰的群组成功").setData(forumgroupId);
    }
    
    /**
     * 查询附近小组(未加入的小组列表)
     * @param longitude
     * @param latitude
     * @param distance
     * @param userId
     * @param offset
     * @param limit
     * @author lixs
     * @Date 2017.8.9
     */
    @RequestMapping(value = "/getNearByGroupsForOtherGroup", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "搜索附近的小组（未加入）", value = "搜索附近的小组（未加入）")
    public ResultMessage<PageData> getNearByGroupsForOtherGroup(@ApiParam("经度") @RequestParam Double longitude,
    														 @ApiParam("纬度") @RequestParam Double latitude,
    														 @ApiParam("距离（米）") @RequestParam Integer distance,
    														 Integer offset,Integer limit,
    														 @RequestHeader(value = "Authorization") String token) {

        logger.info(" 获取我的小组信息!getMyGroups");
//        double distanceD = distance * 1000;
        String userId = JWTUtils.getTokenUserId(token);
      //判断是否有距离设置以及用户是否提供了GPS定位数据
        if ((null != distance) && (null != latitude) && (null != longitude)) {
            logger.info("GPS定位数据以及距离设置数据获取正常！distance=" + distance +
                    ",latitude=" + latitude + ",longitude=" + longitude);

            List<ForumInUserGroupVo> listForumgroup = forumgroupService.getNearByGroupsForOtherGroup(longitude, latitude, distance, userId, offset, limit);
            if (null == listForumgroup) {
                return ResultMessage.newFailure("获取附近的小组信息失败!");
            }
            int listForumgroupTotal = forumgroupService.getNearByGroupsForOtherGroupTotal(longitude, latitude, distance, userId);
            if (0 == listForumgroupTotal) {
                return ResultMessage.newFailure("获取附近的小组信息失败!");
            }
            
            PageData page = new PageData();
            page.setRows(listForumgroup);
            page.setTotal(listForumgroupTotal);
            return ResultMessage.newSuccess("获取附近小组信息成功").setData(page);
        }

        return ResultMessage.newFailure("GPS定位数据异常！");

    }

    /**
     * 百度翻译
     * @param body
     * @param from
     * @param to
     * @author lixs
     * @Date 2017.8.10
     */
    @RequestMapping(value = "/getBaiduResult", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "百度翻译接口", value = "百度翻译接口")
    public ResultMessage<BaiduTranslate> getBaiduResult(String body,String from, String to){
    	
    	if(!StringUtils.hasText(body)){
    		throw new AppException("内容不能为空");
    	}
    	if(!StringUtils.hasText(to)){
    		throw new AppException("目标语种不能为空");
    	}
    	return ResultMessage.newSuccess("成功").setData(BaiduTranslate.getResult(body, from, to));
    }
    
    /**
     * 批量创建系统小组
     * 
     * @param forumgroupBatchVo
     * @author lixs
     * @Date 2017.8.14
     */
    @RequestMapping(value = "/saveSystemForumGroupBatch", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "批量创建系统小组", value = "批量创建系统小组")
    public ResultMessage<Boolean> saveSystemForumGroupBatch(@RequestBody ForumgroupBatchVo forumgroupBatchVo){
    	
    	logger.info("创建系统小组");
    	List<BatchVo> forumgroup = forumgroupBatchVo.getForumgroup();
    	Boolean result = forumgroupService.saveSystemForumGroupBatch(forumgroup);
		if (true == result) {
		    return ResultMessage.newSuccess("批量创建系统小组成功!").setData(result);
		}
		return ResultMessage.newFailure("批量创建系统小组失败!");
    }
    
    /**
     * 查询小组和用户的信息
     * @param groupAndUser
     * @author lixs
     * @Date 2017.8.18
     */
    @RequestMapping(value = "/selectGroupAndUserDetailBatch", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "查询小组和用户的信息", value = "查询小组和用户的信息")
    public ResultMessage<Map<String,Object>> selectGroupAndUserDetailBatch(GroupAndUserList groupAndUser,
    																	   @RequestHeader(value = "Authorization") String token){
    	
    	logger.info("查询小组和用户的信息");
    	List<String> huanxinGroupId = groupAndUser.getHuanxinGroupId();
    	List<String> userIds = groupAndUser.getUserIds();
    	
    	if(null==huanxinGroupId&&null==userIds){
    		Map<String,Object> mapResult = new HashMap<String,Object>();
        	mapResult.put("forumgroup", null);
        	mapResult.put("users", null);
        	return ResultMessage.newSuccess("查询小组和用户的信息成功").setData(mapResult);
    	}
    	
    	List<Forumgroup> forumgroup = forumgroupService.selectGroupAndUserDetailBatch(huanxinGroupId);
    	
    	if(null==userIds&&null!=huanxinGroupId){
    		Map<String,Object> mapResult = new HashMap<String,Object>();
        	mapResult.put("forumgroup", forumgroup);
        	mapResult.put("users", null);
        	return ResultMessage.newSuccess("查询小组和用户的信息成功").setData(mapResult);
    	}
    	
    	com.youdoneed.base.application.ResultMessage<List<String>> friendIds 
    	= friendsClient.isFriendOrNot(userIds.toArray(new String[userIds.size()]));
    	
    	
    	com.youdoneed.base.application.ResultMessage<List<User>> users 
    	= userFeignClient.getUsers(friendIds.getData().toArray(new String[friendIds.getData().size()]));
    	

    	if(null!=userIds&&null==huanxinGroupId){
    		Map<String,Object> mapResult = new HashMap<String,Object>();
        	mapResult.put("forumgroup", null);
        	mapResult.put("users", users.getData());
        	return ResultMessage.newSuccess("查询小组和用户的信息成功").setData(mapResult);
    	}
    	
    	logger.info("用户的信息qweeeeeeeeeeeeeeeeee"+users.getData());
    	Map<String,Object> mapResult = new HashMap<String,Object>();
    	mapResult.put("forumgroup", forumgroup);
    	mapResult.put("users", users.getData());
    	return ResultMessage.newSuccess("查询小组和用户的信息成功").setData(mapResult);
    }
    
  /*  *//**
     * 批量删除系统小组(物理删除)
     * @author lixs
     * @Date 2017.8.19
     *//*
    @RequestMapping(value = "/deleteGroupForSystemBatch", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "批量删除系统小组(物理删除，他人勿用)", value = "批量删除系统小组(物理删除，他人勿用)")
    public ResultMessage<Integer> deleteGroupForSystemBatch(){
    	int result = forumgroupService.deleteGroupForSystemBatch();
    	if(result==0){
    		return ResultMessage.newFailure("删除失败");
    	}
    	return ResultMessage.newSuccess("删除成功").setData(result);
    }*/
    
    /**
     * 获取小组详细信息，包含与用户关联的信息
     * @param forumgroupId
     * @param userId
     * @author lixs
     * @Date 2017.7.31
     */
    @RequestMapping(value = "/findForumgroupDetailsByHuanxinId", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "通过环信id获取小组详细信息，包含与用户关联的信息", value = "通过环信id获取小组详细信息，包含与用户关联的信息")
    public ResultMessage<ForumgroupInUserVo> findForumgroupDetailsByHuanxinId(@ApiParam("环信id")@RequestParam String huanxinId,
    											  							  @ApiParam("用户id")@RequestParam String userId){
    	logger.info("通过环信id获取小组详细信息，包含与用户关联的信息");
    	ForumgroupInUserVo forumgroupInUserVo = forumgroupService.findForumgroupDetailsByHuanxinId(userId, huanxinId);
    	if(null==forumgroupInUserVo){
    		return ResultMessage.newFailure("获取信息失败");
    	}
    	return ResultMessage.newSuccess("获取信息成功").setData(forumgroupInUserVo);
    }
    
    
    /**
     * 逻辑删除单个小组
     * @param forumgroupId
     * @author lixs
     * @Date 2017.10.19
     */
    @RequestMapping(value = "/deleteForumgroup", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "逻辑删除单个小组", value = "逻辑删除单个小组")
    public ResultMessage<Integer> deleteForumgroup(String forumgroupId){
    	logger.info("逻辑删除单个小组");
    	int result = forumgroupService.deleteForumgroup(forumgroupId);
    	if(0==result){
    		return ResultMessage.newFailure("删除小组失败");
    	}
    	return ResultMessage.newSuccess("删除小组成功");
    }
    
    /**
     * 导出群组报表
     * @param groupName
     * @param leaderUserName
     * @param groupType
     * @param groupStyle
     * @param memberCountMin
     * @param memberCountMax
     * @param groupMessageTotalMin
     * @param groupMessageTotalMax
     * @param createDateS
     * @param createDateE
     * @param offset
     * @param limit
     * @param request
     * @param resp
     * @author lixs
     * @Date 2017.10.27
     */
   /* @RequestMapping(value = "/exportGroups", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(notes = "导出群组报表", value = "导出群组报表")
    public void exportGroups(String groupName,String leaderUserName,String groupType,String groupStyle,
				Integer memberCountMin,Integer memberCountMax,Integer groupMessageTotalMin,
				Integer groupMessageTotalMax,String createDateS,String createDateE,Integer offset,
				Integer limit, HttpServletRequest request, HttpServletResponse resp) {
  
        try {
            request.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/x-download");
            String fileName ="group_" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".xlsx";
            resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            List<Forumgroup> result = forumgroupService.selectForumgroup(groupName, leaderUserName, groupType, groupStyle, 
            		memberCountMin, memberCountMax, groupMessageTotalMin, groupMessageTotalMax,createDateS, createDateE, offset, limit);
            ExcelExportUtil<Forumgroup> util = new ExcelExportUtil<Forumgroup>();

            String[] title = {"创建者", "群组名称", "群组介绍","是否公开", "群创建","群组类型", "成员数", "群帖数","地址","创建时间"};
            String[] values = {"leaderUserNickname", "groupName", "groupIntroduction", "privacySetting", "groupType", "groupStyle","memberCount","groupMessageTotal",
            		"address","createDate"};
            int[] widths = {120, 120, 120, 120, 120, 120, 120, 120, 120, 120};
            util.exportExcel(title, values, widths, result, resp.getOutputStream());
            resp.getOutputStream().close();
        } catch (Exception e) {
            logger.error("导出群组报表异常：", e);
            e.printStackTrace();
        }
    }*/
    
}
